package com.scoutmobmap.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MarkerClickHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.ui.SimplePanel;
import com.scoutmobmap.shared.OfferDto;

public class MapPanel extends SimplePanel {
  private boolean mapInitialized = false;
  private boolean dataInitialized = false;
  private List<OfferMarker> offerMarkers = null;
  private List<OfferDto> offerDtos = null;
  private MapWidget map = null;
  
  public MapPanel() {
    Maps.loadMapsApi(
        "ABQIAAAAq3FviAq7L3FE7E3ittDbrBTSWhGO_pZqfyWpkQaEWusrZW2YwhTfMvJziFCbDRJsTYZ3fieGn6P1UA",
        "2", false, new Runnable() {
          public void run() { 
            LatLng sanFrancisco = LatLng.newInstance(37.77, -122.44);
            map = new MapWidget(sanFrancisco, 12);
            map.setSize("100%", "100%");
            map.addControl(new LargeMapControl()); 
            MapPanel.this.setWidget(map);
            if (dataInitialized) { initializeMarkers(); }
            mapInitialized = true;
          }
        }); 
  }
  
  protected void initializeData(List<OfferDto> offers) {
    this.offerDtos = offers;
    if (mapInitialized) { initializeMarkers(); }
    dataInitialized = true;
  }
  
  private void initializeMarkers() {
    offerMarkers = new ArrayList<OfferMarker>();
    for (OfferDto dto : offerDtos) {
      OfferMarker marker = new OfferMarker(dto);
      offerMarkers.add(marker);
      marker.addMarkerClickHandler(new OfferMarkerClickHandler(map));
      map.addOverlay(marker);
    }
    this.setWidget(map);
  }
  
  private static class OfferMarkerClickHandler implements MarkerClickHandler {
    private MapWidget map;
    public OfferMarkerClickHandler(MapWidget map) { this.map = map; }
    
    public void onClick(MarkerClickEvent event) {
      OfferMarker offer = (OfferMarker) event.getSender();
      map.getInfoWindow().open(offer,
          new InfoWindowContent(offer.getInfoWindowWidget()));
    }
  }

}
